<template>
  <div>
    <table-ext :columns="columns" :searchForm="searchForm" :config="config" ref="tableExt" @checkedData="getCheckedData">
      <template slot="table-tip">
        <el-button type="primary" icon="el-icon-plus" @click="addToEnquiry()">加入处理清单</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="openPendingDialog()">待处理清单({{this.pendingCount}})</el-button>
        <div style="margin-left: 10px;">
          <el-dropdown split-button type="primary" @command="handleClick2">
          更多操作
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">手动匹配</el-dropdown-item>
            <el-dropdown-item command="2">关闭记录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <!-- <el-button type="primary" icon="el-icon-success" @click="handMatch()">手动匹配</el-button>
        <el-button type="primary" icon="el-icon-circle-close" @click="closeRecore()">关闭记录</el-button> -->
      </template>
    </table-ext>
    <el-dialog title="重新匹配" :visible.sync="dialogFormVisible" width="60%">
      <span>已选需要手工匹配的清单</span>
      <el-table :data="reMatchPrData" border>
        <el-table-column prop="operation" align ="center" width="80" label="操作">
          <template slot-scope="scope">
            <el-button @click="deleteRow(index)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="srmItemNo" align="center" label="行号" width="80"></el-table-column>
        <el-table-column prop="materialCode" align="center" label="物料编码" width="150"></el-table-column>
        <el-table-column prop="materialName" align="center" label="物料名称" width="250"></el-table-column>
        <el-table-column prop="purchaseQty" align="center" label="需求数量" width="100"></el-table-column>
        <el-table-column prop="purUnitName" align="center" label="单位" width="100"></el-table-column>
        <el-table-column prop="innerOrderNo" align="center" label="内部订单号" width="150"></el-table-column>
        <el-table-column prop="costCenter" align="center" label="成本中心" width="150"></el-table-column>
        <el-table-column prop="matGroupName" align="center" label="物料组" width="200"></el-table-column>
      </el-table>
      <span>可匹配框架协议(请先输入条件后查询)</span>
      <div>
        <el-form :inline="true" :model="reMatchForm" ref="reMatchForm" style="margin-bottom: -20px;">
          <el-form-item label="物料名称:" prop="materialName">
            <el-input v-model="reMatchForm.materialName"></el-input>
          </el-form-item>
          <el-form-item label="供应商:" prop="vendorCode">
            <el-input v-model="reMatchForm.vendorCode"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="reMatchQuery(reMatchForm)">查询</el-button>
            <el-button @click="resetReMatchForm('reMatchForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="reMatchContractData" border style="width: 100%">
          <el-table-column prop="operation" align ="center" width="150" label="操作">
            <template slot-scope="scope">
              <el-button @click="matchRecord(scope.row.id)" type="text" size="small">匹配此纪录</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="contractNo" align="center" label="合同编号" width="150"></el-table-column>
          <el-table-column prop="vendorCode" align="center" label="供应商编码" width="150"></el-table-column>
          <el-table-column prop="vendorName" align="center" label="供应商名称" width="200"></el-table-column>
          <el-table-column prop="materialName" align="center" label="物料名称" width="200"></el-table-column>
          <el-table-column prop="startDate" align="center" label="价格开始日期" width="200"></el-table-column>
          <el-table-column prop="startDate" align="center" label="价格结束日期" width="200"></el-table-column>
          <el-table-column prop="pastDueFlag" align="center" label="过期标记 " width="100" :formatter="pastDueFlag"></el-table-column>
          <el-table-column prop="itemQty" align="center" label="框架数量" width="100"></el-table-column>
          <el-table-column prop="unitPrice" align="center" label="单价" width="100"></el-table-column>
          <el-table-column prop="unitName" align="center" label="单位" width="100"></el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 查看框架关系详情 -->
    <el-dialog title="价格记录" :visible.sync="relationItemVisible" width="60%">
      <el-table :data="relationItemData" border>
        <el-table-column prop="contractCode" align="center" label="合同号" width="150"></el-table-column>
        <el-table-column prop="vendorCode" align="center" label="供应商编码" width="150"></el-table-column>
        <el-table-column prop="vendorName" align="center" label="供应商名称" width="300"></el-table-column>
        <el-table-column prop="materialName" align="center" label="物料描述" width="300"></el-table-column>
        <el-table-column prop="effectiveDateStart" align="center" label="有效开始时间" width="150"></el-table-column>
        <el-table-column prop="effectiveDateEnd" align="center" label="有效截止时间" width="150"></el-table-column>
        <el-table-column prop="pastDueFlag" align="center" label="无效标识" width="150" :formatter="pastDueFlag"></el-table-column>
        <el-table-column prop="itemQty" align="center" label="数量" width="120"></el-table-column>
        <el-table-column prop="taxPrice" align="center" label="单价" width="120"></el-table-column>
        <el-table-column prop="unitName" align="center" label="单位" width="120"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="relationItemVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 待处理对话框 -->
    <el-dialog title="待处理清单" :visible.sync="pendingVisible" width="60%" :default-sort="{prop: 'itemNo', order: 'descending'}" @checkedData="getCheckedData">
      <div style="float: right;margin-bottom: 5px;">
        <el-dropdown split-button type="primary" @command="handleClick">
          更多操作
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">订单</el-dropdown-item>
            <el-dropdown-item command="2">询价</el-dropdown-item>
            <el-dropdown-item command="3">招标</el-dropdown-item>
            <el-dropdown-item command="4">认证</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <el-table :data="pendingData" border>
        <el-table-column type="selection" align="center" width="50"></el-table-column>
        <el-table-column label="序号" align="center" width="60">
            <template slot-scope="scope">
              {{scope.$index + 1}}
            </template>
          </el-table-column>
        <el-table-column prop="prNo" align="center" label="申请单号" width="150"></el-table-column>
        <el-table-column prop="itemNo" align="center" label="行号" width="90"></el-table-column>
        <el-table-column prop="factoryName" align="center" label="工厂" width="200"></el-table-column>
        <el-table-column prop="materialCode" align="center" label="物料编码" width="150"></el-table-column>
        <el-table-column prop="materialName" align="center" label="物料描述" width="300"></el-table-column>
        <el-table-column prop="purUnitName" align="center" label="单位" width="90"></el-table-column>
        <el-table-column prop="purchaseQty" align="center" label="需求数量" width="120"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
  import TableExt from '@/components/common/table-ext/table-ext.vue';
  import TableIcon from '@/components/common/table-ext/table-icon';
  import Vuex from 'vuex'
  export default {
    // 引入自定义表格组件
    components:{
      'table-ext': TableExt
    },
    data() {
      return {
        pendingCount:null,
         // 声明一个有效的id数组集合
        selectedIdArry:[],
        reMatchPrData:[],
        reMatchContractData:[],
        relationItemData:[],
        dialogFormVisible:false,
        relationItemVisible:false,
        pendingVisible:false,
        pendingData:[],
        checkedData: [], // DataGrid选中的数据
        materialData:[], // 发起询价、招标、认证匹配的物料数据
        vendorData:[], // 发起询价、招标、认证匹配的供应商数据
        prItemIds:[],// 重新匹配框架清单ID数组
        // 框架关系data
        relationItemDat:[],
        config:{ // 页面共通配置
          isPage: true, //是否分页
          //title: '无匹配', //页面标题
          isNo: true, //是否显示序号
          selection: true, //是否显示复选框
          crudMapping:{ // CRUD方法
            query:{
              url: this.lib.config.host.prModule + "/purchaserequest/match/loadFrameItems/0/" + this.prId,
              // resultFun(response) { // 修改返回默认值
              //   return {
              //     list: response.data, //返回列表数据
              //     total: response.data.total //返回总数
              //   };
              // }
            },
          }
        },
        // 重新匹配表单对象
        reMatchForm:{
          materialName:'',
          vendorCode:''
        },
        // 查询表单配置
        searchForm:[{
          label: '物料名称:',
          key: 'materialName',
          type: 'input'
        },{
          label: '处理状态:',
          key: 'handleStatus',
          type: 'select',
          dict: [{
            key: '0',
            value: '未处理'
          },{
            key: '1',
            value: '已处理'
          },{
            key: '-1',
            value: '已关闭'
          }]
        }],
        // 表格列定义
        columns:[{
          label: '申请单号',
          key: 'prNo',
          align: 'center',
          width:'150px'
        },{
          label: '行号',
          key: 'itemNo',
          align: 'center',
          width:'100px'
        },{
          label: '工厂',
          key: 'factoryName',
          align: 'center',
          width:'250px'
        },{
          label: '采购组Id',
          key: 'purGroupId',
          align: 'center',
          width:'250px',
          hidden:true
        },{
          label: '采购组',
          key: 'purGroupName',
          align: 'center',
          width:'200px'
        },{
          label: '物料编码',
          key: 'materialCode',
          align: 'center',
          width:'200px'
        },{
          label: '物料描述',
          key: 'materialName',
          align: 'center',
          width:'300px'
        },{
          label: '需求数量',
          key: 'purchaseQty',
          align: 'center',
          width:'100px'
        },{
          label: '单位',
          key: 'purUnitName',
          align: 'center',
          width:'100px'
        },{
          label: '价格记录',
          key: 'frameCount',
          align: 'center',
          width:'150px',
          render:(createElement, params)=>{ // 动态渲染，click事件示例
            let _this = this;
            if(params.row.frameCount > 0){
              return createElement('div', {}, 
                [createElement('el-button', {
                    props: {
                      type: 'text',
                    },
                    on: {
                      click() {
                        _this.openRelationItemDialog(params.row.id)
                      }
                    }
                  }, '(' + params.row.frameCount + ')')
                ]);
            } else {
              return createElement('div', {}, '(0)')
            }
          }
        },{
          label: '申请人',
          key: 'applyerName',
          align: 'center',
          width:'150px'
        },{
          label: '物料组',
          key: 'matGroupName',
          align: 'center',
          width:'200px'
        },{
          label: '处理状态',
          key: 'handleStatus',
          align: 'center',
          width:'150px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
                flag: params.row.handleStatus,
                titles: [{status:0,title:'未受理'},{status:1,title:'已受理'},{status:-1,title:'已关闭'}]
            }});
          }
        },{
          label: '寻源状态',
          key: 'priceSourcingStatus',
          align: 'center',
          width:'150px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
                flag: params.row.priceSourcingStatus,
                titles: [{status:0,title:'未寻源'},{status:2,title:'寻源中'},{status:1,title:'寻源结束'}]
            }});
          }
        },{
          label: '寻源类型',
          key: 'priceSourcingType',
          align: 'center',
          width:'150px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            if(params.row.priceSourcingType === 1){
              return createElement('div', {}, '询价');
            } else if(params.row.priceSourcingType === 2){
              return createElement('div', {}, '招投标');
            } else if(params.row.priceSourcingType === 3){
              return createElement('div', {}, '竞价');
            } else {
              return createElement('div', {}, '其他');
            }
          }
        },{
          label: '合同状态',
          key: 'contractStatus',
          align: 'center',
          width:'150px',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            return createElement(TableIcon,{props:{
                flag: params.row.contractStatus,
                titles: [{status:0,title:'未签订'},{status:1,title:'已签订'}]
            }});
          }
        },{
          label: '申请备注',
          key: 'remarks',
          align: 'center',
          width:'300px'
        }]
      };
    },
    props:['prId'],
    mounted() {

    },
    methods: {
      // 关闭记录
      closeRecore(){
        let isRequest = true;
        if(this.checkedData.length <= 0){
          this.$message({
            type:'warning',
            message:'请选择记录进行关闭!'
          })
        } else {
          this.checkedData.map(item =>{
            if(item.closeStatus === 1){
              this.$message({
                type:'warning',
                message:'申请单号:' + item.prNo + '行号:' + item.itemNo + ',已关闭无法重复关闭！'
              })
              return isRequest = false;
            }
            // 已处理，无法关闭
            if(item.handleStatus === 1){
              this.$message({
                type:'warning',
                message:'申请单号:' + item.prNo + '行号:' + item.itemNo + ',已处理无法关闭！'
              })
              return isRequest = false;
            }
            this.selectedIdArry.push(item.id);
          });
          if(isRequest){ //是否发起请求
            this.$confirm('此操作将关闭记录！, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.axios.post(this.lib.config.host.prModule + '/purchaserequest/match/effectFrame/markHandled/close', this.selectedIdArry).then((res)=>{
                if(res.data.success){
                  this.$message({
                    type: 'success',
                    message: '关闭成功!'
                  });
                  this.$refs['tableExt'].refreshTable();
                }
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消此次操作!'
              });
            });
          }
        }
      },
      // 手动匹配
      handMatch(){
        this.dialogFormVisible = true;
        this.reMatchPrData = this.checkedData;
      },
      // 打开待处理对话框
      openPendingDialog(){
        this.pendingVisible = true;
      },
       // 删除重新匹配行
      deleteRow(index) {
        this.reMatchPrData.splice(index, 1);
      },
      // 重置重新匹配查询表单内容
      resetReMatchForm(formObj){
        this.resetForm(formObj);
      },
      // 重新匹配查询
      reMatchQuery(reMatchForm){
        this.axios.post(this.lib.config.host.prModule + '/purchaserequest/match/noFrame/loadContractItem/' + this.prId, reMatchForm)
        .then(res => {
            this.reMatchContractData = res.data.rows;
          }).catch(error => {
            this.$message({
              type:'error',
              message:error
          })
        });
      },
      // 过期标识格式化
      pastDueFlag(row, column){
        if(column === 0){
            return '有效';
        } else {
           return '无效';
        }
      },
      // 匹配记录
      matchRecord(contractItemId){
        this.reMatchPrData.map(item =>{
          this.prItemIds.push(item.id);
        });
        this.axios.post(this.lib.config.host.prModule + '/purchaserequest/match/reMatch/matchRecord/' + contractItemId, this.prItemIds)
        .then(res => {
          if(res.data.success){
            this.$message({
              type:'success',
              message:"匹配成功！"
            })
          } else {
            this.$message({
              type:'error',
              message:res.data.message
            })
            }
          }).catch(error => {
            this.$message({
              type:'error',
              message:error
          })
        });
      },
      // 打开框架关系详情对话框
      openRelationItemDialog(id){
        this.axios.post(this.lib.config.host.prModule + '/purchaserequest/match/frames/viewRelationItem/' + id)
        .then(res => {
          this.relationItemData = res.data.result;
        }).catch(error => {
          this.$message({
            type:'error',
            message:error
          })
        });
        this.relationItemVisible = true;
      },
      handleClick(type) {
        switch(type){
          case "1" :
            alert('订单！')
            break;
          case "2" :
            //this.$router.push({name:'ToEnquiryDetail'});
            this.toEnquiry(); // 转询价
            break;
          case "3":
            this.toBid();
            break;
          case "4":
            this.toNpcTask()
            break;
        }
      },
      // 获取选中行的数据（子组件传递）
      getCheckedData(data){
        this.checkedData = data;
      },
       // 加入到待询价清单里
      addToEnquiry(){
       if(this.checkedData.length <= 0){
          this.$message({
            type: 'warning',
            message: '请选择数据!'
          });
       }  else {
          this.checkedData.forEach((element1)=>{
            let isContain = false;
            let isAllow = true;
            if(this.pendingData.length > 0){
              this.pendingData.forEach((element2)=>{
                if(element2.factoryId !== element1.factoryId && element2.purGroupId !== element1.purGroupId){ // 过滤不同工厂和采购组数据
                  isAllow = false;
                  return;
                }
                if(element2.prNo === element1.prNo && element2.itemNo === element1.itemNo){ // 过滤重复加入数据
                  isContain = true;
                  return;
                }
              })
            }
            if(!isContain && isAllow){
              this.pendingData.push(element1);
              this.pendingCount = this.pendingData.length;
            }
          })
        }
      },
      // 转询比价
      toEnquiry(){
        // 转物料认证页面
        let validateResult = this.turnBeforValidateResult();
        if(validateResult){ // 验证通过方可执行
          this.loadMaterials();
          this.loadVendors();
          this.$confirm('确认发起询价嘛？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$router.push({path: '/Index/Rfq/AddRfqEnquiry', query:{'routerSource':'prRequest','materialData': this.materialData,'vendorData': this.vendorData}});
            //this.$router.push({path: '/Index/VendorDlv/Npc/Buyer/Withmtrl/Add/Tab', query:{'checkedData': this.checkedData}})
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消操作!'
            });
          });
        }
      },
       // 转询比价
      toBid(){
        // 转物料认证页面
        let validateResult = this.turnBeforValidateResult();
        if(validateResult){ // 验证通过方可执行
          this.loadMaterials();
          this.loadVendors();
          this.$confirm('确认发起招标嘛？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$router.push({name:'creatBid', query:{'routerSource':'prRequest','materialData': this.materialData,'vendorData': this.vendorData}});
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消操作!'
            });
          });
        }
      },
      // 页面初始化加载物料
      loadMaterials() {
        this.axios.post(this.lib.config.host.prModule + '/purchaserequest/match/toEnquiry/loadMaterials',this.selectedIdArry)
        .then((res)=>{
          if(res.data.success){
            this.materialData = res.data.result;
            //store.commit('storeMaterialData', this.materialData);
          }
         // this.materialData = res.data;
        })
        .catch((error)=>{
          console.log(error);
        })
      },
      // 页面初始化加载供应商
      loadVendors() {
        this.axios.post(this.lib.config.host.prModule + '/purchaserequest/match/toEnquiry/loadVendors', this.selectedIdArry)
        .then((res)=>{
          if(res.data.success){
            this.vendorData = res.data.result;
            //store.commit('storeVendorData', this.vendorData);
          }
        })
        .catch((error)=>{
          console.log(error);
        })
      },
      // 转物料认证
      toNpcTask(){
        //this.$router.push({name:'AddNpcTaskTab'});
        // 转物料认证页面
        let validateResult = this.turnBeforValidateResult();
        if(validateResult){ // 验证通过方可执行
          this.$confirm('确认转物料认证嘛？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$router.push({path: '/Index/VendorDlv/Npc/Buyer/Withmtrl/Add/Tab', query:{'checkedData': this.checkedData}})
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消操作!'
            });
          });
        }
      },
      // 跳转前数据可行性验证
      turnBeforValidateResult() {
        let validateResult = true;
        if(this.checkedData.length <= 0){
          this.$message({
            type: 'warning',
            message: '请选择数据!'
          });
          return validateResult = false;
        } else {
          const purGroupId = this.checkedData[0].purGroupId;
          const factoryId = this.checkedData[0].factoryId;
          this.checkedData.forEach(element =>{
            // 数据采购组需保持一致
            if(purGroupId != element.purGroupId){
              this.$message({
                type: 'warning',
                message: '采购组选择不一致，请筛选数据!'
              });
              return validateResult = false;
            }
            // 数据品类需保持一致
            if(factoryId != element.factoryId){
              this.$message({
                type: 'warning',
                message: '工厂选择不一致，请筛选数据!'
              });
              return validateResult = false;
            }  
            this.selectedIdArry.push(element.id);
          })
        }
        return validateResult;
      },
      handleClick2(type) {
        switch(type){
          case "1" :
            this.handMatch()
            break;
          case "2":
            this.closeRecore();
            break;
        }
      },
    }
  }
   // vuex存储初始化数据
  const store = new Vuex.Store({
    state: {
        materialData : [],
        vendorData : []
    },
    mutations: {
        storeMaterialData (state,materialData) {
            state.materialData = materialData;
        },
        storeVendorData (vendorData) {
            state.vendorData = vendorData;
        },
    }
  });
</script>